<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="站点名称" prop="siteName">
          <el-input
            v-model="queryParams.siteName"
            placeholder="请输入站点名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="站点状态" clearable>
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="季节" prop="status">
          <el-select v-model="queryParams.dictValue" placeholder="季节状态" clearable>
            <el-option
              v-for="dict in seasonList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="车辆" prop="status">
          <!-- {{ queryParams.dictValue }} -->
          <el-select v-model="vehicle" placeholder="车辆状态" clearable>
            <el-option
            v-for="dict in filteredFoodSite"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
   
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5" style="display: flex;">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            style="height: 40px;margin-top: 5px;"
            @click="handleAdd"
            v-hasPermi="['food:site:add']"
          >新增</el-button>
           <!-- <div style="font-size: 15px;margin-top: 5px;margin-left: 30px;">
              旺季时间：{{ listfoodTime[0].begin_date + "---" + listfoodTime[0].end_date }}
           </div>
           <div style="font-size: 15px;margin-top: 5px;margin-left: 30px">
              淡季时间：{{ listfoodTime[1].begin_date + "---" + listfoodTime[1].end_date }}
           </div> -->
   <div class="season-time-container" v-if="listfoodTime.length > 0">
    <div class="season-time busy-season">
      <span class="season-label">旺季时间：</span>
      <span class="time-range" v-if="!editingBusy">
        {{ listfoodTime[0].begin_date }} 至 {{ listfoodTime[0].end_date }}
      </span>
      <el-date-picker
        v-else
        v-model="tempBusyTime"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        size="mini"
        style="width: 280px"
      ></el-date-picker>
      <el-button
        type="text"
        @click="handleEditSeason(listfoodTime[0].id)"
      >
      <i class="el-icon-edit" v-if="!editingBusy"></i>
      <span v-else>确定</span>
    </el-button>
    </div>

    <div class="season-time off-season">
      <span class="season-label">淡季时间：</span>
      <span class="time-range" v-if="!editingOff">
        {{ listfoodTime[1].begin_date }} 至 {{ listfoodTime[1].end_date }}
      </span>
      <el-date-picker
        v-else
        v-model="tempOffTime"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        size="mini"
        style="width: 280px"
      ></el-date-picker>
      <el-button
        type="text"
        @click="handleEditSeason(listfoodTime[1].id)"
      >
      <i class="el-icon-edit" v-if="!editingOff"></i>
     <span v-else>确定</span>
    </el-button>
    </div>
  </div>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="deptList"
        row-key="deptId"
      >
        <el-table-column prop="siteName" label="站点名称" ></el-table-column>
        <el-table-column prop="orderNum" label="排序" ></el-table-column>
        <el-table-column prop="status" label="状态" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="dictValue" label="季节">
          <template slot-scope="scope">
            <span v-if="scope.row.dictValue && scope.row.dictValue != 5">
              旺季
            </span>
            <span v-if="scope.row.dictValue1 && scope.row.dictValue1 != 5">
              淡季
            </span>
            <span v-if="scope.row.dictValue1 == 5 || scope.row.dictValue == 5">
              不分淡旺季
            </span>
          </template>
        </el-table-column> -->
        <el-table-column prop="dictValue" label="旺季车辆">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.food_site" :value="scope.row.dictValue"/>
            <!-- {{ dict.type.food_site.filter(el=>) }} -->
            <!-- dictValue -->
          </template>
        </el-table-column>

        <el-table-column prop="dictValue" label="淡季车辆">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.food_site" :value="scope.row.dictValue1"/>
            <!-- {{ dict.type.food_site.filter(el=>) }} -->
            <!-- dictValue -->
          </template>
        </el-table-column>
      
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['food:site:edit']"
            >修改</el-button>
            <el-button
              v-if="scope.row.parentId != 0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['food:site:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--   
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination-container"
      ></el-pagination> -->
      <div>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

      </div>
  
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="站点名称" prop="siteName">
                <el-input v-model="form.siteName" placeholder="请输入站点名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示排序" prop="orderNum">
                <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="负责人" prop="leader">
                <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
              </el-form-item>
            </el-col> -->
       
            <el-col :span="12">
              <el-form-item label="站点状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.dictValue1 != 5">
            <el-col :span="12">
              <el-form-item label="车辆" prop="dictValue">
                <!-- <dict-tag :options="dict.type.food_site" :value="scope.row.dictValue"/> -->
          <!-- {{ form.dictValue1 }} -->

                <el-select v-model="form.dictValue" placeholder="请选择车辆" clearable>
                    <el-option
                      v-for="dict in dict.type.food_site.filter(el=> el.value == 1 || el.value == 2 || el.value == 5)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="季节">
                  <!-- <span v-if="form.dictValue">
                    {{ form.dictValue == 1 || form.dictValue == 2 || form.dictValue == 3 ? "旺季" : (form.dictValue == 4 ? "淡季" : "不分淡旺季")}}
                  </span> -->
                  <!-- <span v-else>
                    选择车辆后显示
                  </span> -->
                  {{ form.dictValue == 5 ? "不分淡旺季" : "旺季" }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.dictValue1 == 5 && form.dictValue == 5">
            <el-col :span="12">
              <el-form-item label="车辆" prop="dictValue">
                <!-- <dict-tag :options="dict.type.food_site" :value="scope.row.dictValue"/> -->
                <el-select v-model="form.dictValue" placeholder="请选择车辆" clearable @change="onChange">
                    <el-option
                      v-for="dict in dict.type.food_site.filter(el=> el.value == 1 || el.value == 2 || el.value == 5)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="季节">
                  <!-- <span v-if="form.dictValue">
                    {{ form.dictValue == 1 || form.dictValue == 2 || form.dictValue == 3 ? "旺季" : (form.dictValue == 4 ? "淡季" : "不分淡旺季")}}
                  </span> -->
                  <!-- <span v-else>
                    选择车辆后显示
                  </span> -->
                  {{ form.dictValue == 5 ? "不分淡旺季" : "旺季" }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.dictValue != 5">
            <el-col :span="12">
              <el-form-item label="车辆" prop="dictValue1">
                <!-- <dict-tag :options="dict.type.food_site" :value="scope.row.dictValue"/> -->
                <el-select v-model="form.dictValue1" placeholder="请选择车辆" clearable>
                    <el-option
                      v-for="dict in opinstiList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="季节">
                  <!-- 淡季 -->
                  {{ form.dictValue1 == 5 ? "不分淡旺季" : "淡季" }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild,listfood,uodateFood } from "@/api/system/station"
  import Treeselect from "@riophae/vue-treeselect"
  import "@riophae/vue-treeselect/dist/vue-treeselect.css"
  
  export default {
    name: "Dept",
    dicts: ['sys_normal_disable',"food_site"],
    components: { Treeselect },
    data() {
      return {
        loading: true,
        showSearch: true,
        deptList: [],
        vehicle: "",
        opinstiList: [
          {
            value: "4",
            label:"第一辆车"
          },
          {
            value: "5",
            label: "食堂"
          }
        ],
        total: 0,
        deptOptions: [],
        title: "",
        listfoodTime: [],
        editingBusy: false,
    editingOff: false,
    tempBusyTime: [],
    tempOffTime: [],
        seasonList: [
          {
            label: "淡季",
            value: "'1','5'"
          },
          {
            label: "旺季",
            value: "'1','2','5'"
          },
        ],
        open: false,
        isExpandAll: true,
        refreshTable: true,
          queryParams: {
            siteName: undefined,
          status: undefined,
          pageNum: 1,
          pageSize: 10
        },
        form: {},
        rules: {
          parentId: [
            { required: true, message: "上级站点不能为空", trigger: "blur" }
          ],
          siteName: [
            { required: true, message: "站点名称不能为空", trigger: "blur" }
          ],
          dictValue1: [
            { required: true, message: "车辆不能为空", trigger: "blur" }
          ],
          dictValue: [
            { required: true, message: "车辆不能为空", trigger: "blur" }
          ],
          orderNum: [
            { required: true, message: "显示排序不能为空", trigger: "blur" }
          ],
          email: [
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"]
            }
          ],
          phone: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ]
        }
      }
    },
    created() {
      this.getList()
      listfood().then(el => {
        this.listfoodTime = el.data
      })
    },
    computed: {
    filteredFoodSite() {
      if (!this.queryParams.dictValue) return this.dict.type.food_site;

      const allowedValues = this.queryParams.dictValue
  .replace(/'/g, '')  // 去掉所有单引号，变成 "1,2,5"
  .split(',')         // 变成 ["1", "2", "5"]
  .map(String);       // 变成 [1, 2, 5]

        console.log(allowedValues)
        // return
        const T = this.dict.type.food_site.filter(el =>
        // console.log(el.value)
          allowedValues.includes(el.value)
        );

        this.vehicle = "";
        return T;
      console.log(T)
    }
  },
    methods: {
      async updateFooTime(type,val,val1) {
        await uodateFood({
                beginDate: val,
                endDate: val1,
                type: type,
                id:Number(type)
              })
      },
      formatDate(date) {
        return dayjs(date).format('YYYY-MM-DD')
      },
      onChange() {
        if (this.form.dictValue !=5) {
          this.form.dictValue1 = "";
          this.form.dictLabel1 = "";
        }
      },
      handleEditSeason(type) {
        if (type == 1) {
          console.log(type)
          this.editingBusy = !this.editingBusy
          if (this.editingBusy) {
            this.tempBusyTime = [this.listfoodTime[0].begin_date, this.listfoodTime[0].end_date]
          } else {
            // 保存修改
            this.$confirm('确定要修改旺季时间吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              console.log(66)
              
              this.listfoodTime[0].begin_date = this.tempBusyTime[0]
              this.listfoodTime[0].end_date = this.tempBusyTime[1]
              this.updateFooTime(type,this.tempBusyTime[0],this.tempBusyTime[1])
             
              // 这里调用API保存修改
              this.$message.success('旺季时间已更新')
            }).catch(() => {
              this.editingBusy = true // 取消后保持编辑状态
            })
          }
        } else {
          this.editingOff = !this.editingOff
          if (this.editingOff) {
            this.tempOffTime = [this.listfoodTime[1].begin_date, this.listfoodTime[1].end_date]
          } else {
            // 保存修改
            this.$confirm('确定要修改淡季时间吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.updateFooTime(type,this.tempOffTime[0],this.tempOffTime[1])

              this.listfoodTime[1].begin_date = this.tempOffTime[0]
              this.listfoodTime[1].end_date = this.tempOffTime[1]
              // 这里调用API保存修改
              this.$message.success('淡季时间已更新')
            }).catch(() => {
              this.editingOff = true // 取消后保持编辑状态
            })
          }
        }
      },
      getList() {
        this.loading = true
        if (this.queryParams.dictValue) {
        this.queryParams.dictValue = String(this.queryParams.dictValue)
        }
        // if (this.vehicle) {
        // this.queryParams.dictValue = `'${this.vehicle}'`
        let T = {

        }
        if (this.vehicle) {
          // console.log(this.vehicle)
          if (this.vehicle == 1 || this.vehicle == 2) {
             T.dictValue = this.vehicle
          } else if(this.vehicle == 4){
            T.dictValue1 = 1
          } else {
            if (this.queryParams.dictValue == "'1','2','5'") {
                 T.dictValue = this.vehicle
            } else {
                T.dictValue1 = this.vehicle
            }
          }
        } else {
            if (this.queryParams.dictValue == "'1','2','5'") {
              T.dictValue = "'1','2','5'"
            }else if(this.queryParams.dictValue == "'1','5'"){
                T.dictValue1 = "'1','5'"
            }
        }
        console.log(T)
      
        // }
        listDept({...this.queryParams,...T}).then(response => {
          this.deptList = response.rows
          this.total = response.total
          this.loading = false
        }).catch(() => {
          this.loading = false 
        })
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.deptId,
          label: node.siteName,
          children: node.children
        }
      },
      cancel() {
        this.open = false
        this.reset()
      },
      reset() {
        this.form = {
          deptId: undefined,
          parentId: undefined,
          siteName: undefined,
          orderNum: undefined,
          leader: undefined,
          phone: undefined,
          email: undefined,
          status: "0"
        }
        this.resetForm("form")
      },
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      resetQuery() {
        this.resetForm("queryForm")
        this.queryParams.pageNum = 1
        this.queryParams.pageSize = 10
        this.handleQuery()
      },
      handleAdd(row) {
        this.reset()
        if (row != undefined) {
          this.form.parentId = row.deptId
        }
        this.open = true
        this.title = "添加站点"
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.rows, "deptId")
        })
      },
      toggleExpandAll() {
        this.refreshTable = false
        this.isExpandAll = !this.isExpandAll
        this.$nextTick(() => {
          this.refreshTable = true
        })
      },
      handleUpdate(row) {
        this.reset()
        getDept(row.id).then(response => {
          this.form = response.data
          console.log(this.form.dictValue1)
          if (this.form.dictValue1 == 1) {
            this.form.dictValue1 = String(4)
          }
          console.log(this.form)
          this.$nextTick(() => {
            this.open = true
          this.title = "修改站点"
          })
        //   listDeptExcludeChild(row.id).then(response => {
        //     this.deptOptions = this.handleTree(response.rows, "deptId")
        //     if (this.deptOptions.length == 0) {
        //       const noResultsOptions = { deptId: this.form.parentId, siteName: this.form.parentName, children: [] }
        //       this.deptOptions.push(noResultsOptions)
        //     }
        //   })
        })
      },
      submitForm() {
        this.$refs["form"].validate(valid => {
          console.log(valid)
          if (!valid) {
            return
          }
          // form.dictValue
          console.log(this.dict.type.food_site)
          if (this.form.dictValue == 5 || this.form.dictValue1 == 5) {
            this.form.dictValue = 5;
            this.form.dictValue1 = 5;
            this.form.dictLabel = "食堂";
            this.form.dictLabel1 = "食堂";
          } else {
            const T = this.dict.type.food_site.filter(el => el.value == this.form.dictValue)
              if (T.length > 0) {
                this.form.dictLabel = T[0].label
              }
              const Ts = this.dict.type.food_site.filter(el => el.value == this.form.dictValue1)
              if (Ts.length > 0) {
                this.form.dictLabel1 = Ts[0].label
              }
          }

          if (this.form.dictValue1 == 4) {
            this.form.dictValue1 = "1"
          }
          if (valid) {
            if (this.form.id != undefined) {
              updateDept(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addDept(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      handleDelete(row) {
        this.$modal.confirm('是否确认删除名称为"' + row.siteName + '"的数据项？').then(() => {
          return delDept(row.id)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      },
      handleSizeChange(val) {
        this.queryParams.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.queryParams.pageNum = val
        this.getList()
      }
    }
  }
  </script>
  
  <style scoped>
  .pagination-container {
    margin-top: 20px;
    text-align: center;
  }
  .season-time-container {
  display: flex;
  gap: 20px;
  margin-left: 30px;
}

.season-time {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.busy-season {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #e1f3d8;
}

.off-season {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #e9e9eb;
}

.season-label {
  font-weight: bold;
  margin-right: 5px;
}

.time-range {
  margin-right: 5px;
}
  </style>